package com.feigu.repository.good.impl;

import com.feigu.entity.Goods;
import com.feigu.repository.good.GoodRepository;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lijiaosheng on 2017/10/13.
 */
@Repository
public class GoodRepositoryImpl implements GoodRepository {

    private static final  String INDEX_NAME="goods";

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    public void setElasticsearchTemplate(ElasticsearchTemplate elasticsearchTemplate) {
        this.elasticsearchTemplate = elasticsearchTemplate;
    }

    public void createIndex() {
        elasticsearchTemplate.deleteIndex(Goods.class);
        elasticsearchTemplate.createIndex(Goods.class);
        elasticsearchTemplate.putMapping(Goods.class);
    }


    public void delete(String id) {
        elasticsearchTemplate.delete(Goods.class, id);
    }

    public void index(IndexQuery query) {
        elasticsearchTemplate.index(query);
    }

    public void update(Goods goods) {
        List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
        IndexQuery indexQuery = new IndexQueryBuilder().withId(goods.getId()).withIndexName(INDEX_NAME).withObject(goods).build();
        indexQueries.add(indexQuery);
        try {
            elasticsearchTemplate.bulkIndex(indexQueries);
            elasticsearchTemplate.refresh(Goods.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<Goods> searchGoodsByCatName(String catName) {
        NativeSearchQueryBuilder searchQuery = new NativeSearchQueryBuilder();
        BoolQueryBuilder bqb = QueryBuilders.boolQuery();
        searchQuery.withIndices(INDEX_NAME);
        searchQuery.withPageable(new PageRequest(1, 20));
        bqb.mustNot(QueryBuilders.termQuery("catname", catName));
        List<Goods> list = elasticsearchTemplate.queryForList(searchQuery.build(), Goods.class);
        return list;
    }


}
